package com.lzk.jetpacktest.code

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import com.lzk.jetpacktest.R
import com.lzk.jetpacktest.databinding.ActivityVerificationCodeBinding

/**
 * @Author: LiaoZhongKai
 * @Date: 2021/8/18 9:22
 * @Description: 验证码页面
 */
class VerificationCodeActivity : AppCompatActivity() {

    companion object{
        private const val COUNT_DOWN_TIME = 60*1000L
    }

    private lateinit var mBinding: ActivityVerificationCodeBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = DataBindingUtil.setContentView(this,R.layout.activity_verification_code)
        initView()
        initEvent()
    }

    //千万不要忘记在onDestroy中取消倒计时
    //千万不要忘记在onDestroy中取消倒计时
    //千万不要忘记在onDestroy中取消倒计时
    override fun onDestroy() {
        super.onDestroy()
        CodeCountDownUtil.cancel()
    }

    private fun initView(){
        //如果当前时间仍在倒计时范围内，则显示倒计时
        if (CodeCountDownUtil.isCounting()){
            CodeCountDownUtil.start(CodeCountDownUtil.getCountTimeMills(),mCountDownListener)
            mBinding.btn.isEnabled = false
        }else{//否则显示获取验证码
            mBinding.btn.text = "获取验证码"
        }
    }

    private val mCountDownListener = object : CodeCountDownUtil.OnCountDownListener{
        override fun onTick(seconds: Long) {
            Log.d("TAG","onTick:${seconds}")
            mBinding.btn.text = "$seconds 秒后重新获取"
        }

        override fun onFinish() {
            mBinding.btn.isEnabled = true
            mBinding.btn.text = "获取验证码"
        }

    }

    private fun initEvent(){

        //获取验证码按钮
        mBinding.btn.setOnClickListener {
            //模拟验证码发送成功
            Toast.makeText(this,"验证码已发送",Toast.LENGTH_SHORT).show()
            //按照正常流程，以下代码应该在验证码发送成功之后再调用
            //开始倒计时
            CodeCountDownUtil.start(COUNT_DOWN_TIME,mCountDownListener)
            mBinding.btn.isEnabled = false
        }

        //重置验证码
        //模拟登录成功后要重置
        mBinding.btnReset.setOnClickListener {
            CodeCountDownUtil.reset()
            mBinding.btn.isEnabled = true
            mBinding.btn.text = "获取验证码"
        }
    }

}